/**
 * Javscript Source code file for messages.php
 */

// global variable for this screen
var selected_key = 0;
var data_grid = null;
var published_keys = new Array();
var filter_active = false;
var filter = new Array(3);
var current_filter_value = new Array(3);

function galaxytool_messages_init() {
	
	dojo.connect(dijit.byId("grid1"), "_onFetchComplete", galaxytool_grid_on_fetch_complete );
	dojo.connect(dijit.byId("grid1"), "onCellDblClick", galaxytool_handle_cellDblClick );
	dojo.connect(dijit.byId("grid1"), "onRowClick", galaxytool_handleRowSelect );
	dojo.connect(dijit.byId("grid1"), "onFetchError", handle_dojo_errors );

	dojo.connect(dijit.byId("delete_button"), "onClick", galaxytool_delete_message );
	dojo.connect(dijit.byId("publish_button"), "onClick", galaxytool_publish_message );
	dojo.connect(dijit.byId("filter_button"), "onClick", galaxytool_filtericon_click );
	
	
	filter[0] = dijit.byId("filter_playername");
	filter[1] = dijit.byId("filter_subject");
	filter[2] = dijit.byId("filter_messagetime");

	for (var i=0;i<3;i++) {
		current_filter_value[i] = filter[i].get("value");
		dojo.connect(filter[i], "onBlur", galaxytool_handle_filterchange );
		dojo.connect(filter[i], "onKeyPress", galaxytool_handle_filterchange );
	}
}
dojo.ready(galaxytool_messages_init);

function galaxytool_filtericon_click() {
	if (filter_active == false) {
		filter_active = true;
		dojo.byId("filter_pane").style.display = "inline";
	} else {
		dojo.byId("filter_pane").style.display = "none";

		grid1.filter({
			playername: "*",
			subject: "*",
			messagetime: "*"
		});
		filter_active = false;

		// reset filter at input field and buffer
		for(var i=0; i<3; i++) {
			current_filter_value[i] = "*";
			if (i==0) {
				filter[i].set("value", "*"); // playername shall get * on screen
			} else {
				filter[i].set("value", "");
			}
		}

	}
}

function galaxytool_grid_on_fetch_complete() {

	if (grid1.get("rowCount") > 0) {
		// select first item when fetch is complete
		grid1.selection.addToSelection(0);

		// get message id
		var value = grid1.store.getValue(grid1.selection.getFirstSelected(), "id");

		data_grid = grid1;

		// load content if data selection has changed since last fetch
		if (value != null && selected_key != value) {
			galaxytool_load_content(value);
		}

		selected_key = value;
	} else {
		grid1.selection.deselectAll();
		selected_key        = null;

		// disable buttons and cleanup message area (no message is selected)
		dijit.byId("publish_button").set('disabled', true);
		dijit.byId("delete_button").set('disabled', true);
		dojo.byId("gridContentPane").innerHTML = "";
	}
}

function galaxytool_publish_message() {
	// disable button
	dijit.byId("publish_button").set('disabled', true);

	var source_url = "ajax/ajax_messages.php?type=publish&id="+selected_key;
	var xhrArgs = {
	        url: source_url,
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// store published id to disable button for this message until page is left
					published_keys[selected_key] = true;
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}

function galaxytool_delete_message() {
	// disable buttons and cleanup message area (no message will be selected)
	dijit.byId("publish_button").set('disabled', true);
	dijit.byId("delete_button").set('disabled', true);
	dojo.byId("gridContentPane").innerHTML = "";

	var source_url = "ajax/ajax_messages.php?type=delete&id="+selected_key;
	var xhrArgs = {
	        url: source_url,
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// reload grid pane by deleting item from grid
					var items = data_grid.selection.getSelected();
					if (items.length) {
						dojo.forEach(items, function(selectedItem) {
							if (selectedItem !== null) {
								store1.deleteItem(selectedItem);
							}
						});
					}
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
}

function galaxytool_handle_filterchange(e) {
	if (e != null && e.keyCode != 13) {
		return; // ignore onKeyPress event if other keys than ENTER are hit
	}

	var changed = false;
	// check if filter values have changed
	for (var i=0;i<3;i++) {
		if (filter[i].get("value") != current_filter_value[i] && !(filter[i].get("value") == "" && current_filter_value[i] == "*")) changed = true;
	}

	if (changed == false) return;

	// copy filter values
	for (var i=0;i<3;i++) {
		current_filter_value[i] = filter[i].get("value");
		if (current_filter_value[i] == "") current_filter_value[i] = "*";
	}

	// set filter:
	grid1.queryOptions = {ignoreCase: true};
	grid1.filter({
		playername: current_filter_value[0],
		subject: current_filter_value[1],
		messagetime: current_filter_value[2]
	});


}

function galaxytool_handleRowSelect(e)
{
	// get message id
	var value = e.grid.store.getValue(e.grid.getItem(e.rowIndex), "id");

	if (selected_key == value) return; // no refresh needed
	selected_key = value;
	data_grid = e.grid;

	galaxytool_load_content(value);
}

function galaxytool_handle_cellDblClick(e) {
	var rowindex = e.rowIndex;
	if (rowindex == null) return;

	filter_active = true;
	switch(e.cellIndex) {
		case 0:
			filter[0].set("value", grid1.store.getValue(grid1.getItem(rowindex), "playername"));
			break;
		case 1:
			filter[1].set("value", grid1.store.getValue(grid1.getItem(rowindex), "subject"));
			break;
		case 2:
			var messagetime = grid1.store.getValue(grid1.getItem(rowindex), "messagetime");
			var messagetime = messagetime.substring(0, 10)+"*"; // only use date + asterix for filter

			filter[2].set("value", messagetime);
			break;
	}

	dojo.byId("filter_pane").style.display = "inline"; // show filter area

	galaxytool_handle_filterchange(); // apply filter

}

function galaxytool_load_content(value) {
	// load message into message area
	var source_url = "ajax/ajax_messages.php?type=content&id="+value;
	var xhrArgs = {
	        url: source_url,
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		dojo.byId("gridContentPane").innerHTML = jsonData.result;

	    			if (published_keys[selected_key] != null) {
	    				dijit.byId("publish_button").set('disabled', true);
	    			} else {
	    				dijit.byId("publish_button").set('disabled', false);
	    			}
	    			dijit.byId("delete_button").set('disabled', false);
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
}

function handle_dojo_errors(e) {
	console.log("fetch error:");
	console.log(e);
}